package com.hrs.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hrs.common.constant.RedisConstants;
import com.hrs.enity.db.Privilege;
import com.hrs.core.service.PrivilegeService;
import com.hrs.core.mapper.PrivilegeMapper;
import com.hrs.third.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
* @author 纱雾休比酱
* @description 针对表【t_privilege(系统功能表)】的数据库操作Service实现
* @createDate 2022-12-05 23:04:48
*/
@Service
public class PrivilegeServiceImpl extends ServiceImpl<PrivilegeMapper, Privilege>
    implements PrivilegeService{

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Autowired
    private RedisService redisService;
    @Autowired
    private PrivilegeMapper privilegeMapper;

    @Override
    public boolean checkRoleHavePrivilege(Integer roleId, String requestURI) {
        String key = RedisConstants.ROLE_PRIVILEGE + roleId;
        List<String> privileges = redisService.getList(key, String.class);

        //重构权限集合
        if(privileges.size() == 0){
            String lockKey = RedisConstants.LOCK + key;
            try {
                boolean tryLock = redisService.tryLock(lockKey);
                if(tryLock){
                    privileges = listRolePrivilege(roleId);
                    redisService.set(key,privileges,30, TimeUnit.DAYS);
                } else {
                    checkRoleHavePrivilege(roleId,requestURI);
                }
            } catch (Exception e){
                e.printStackTrace();
            } finally {
                redisService.unlock(lockKey);
            }
        }

        for(String url : privileges){
            if(PATH_MATCHER.match(url,requestURI)){
                return true;
            }
        }

        return false;
    }

    public List<String> listRolePrivilege(Integer roleId){
        return privilegeMapper.listUrlByRoleId(roleId);
    }
}




